import LoggerUtil from './LoggerUtil';

export default class Util {

    static isNumberAndWord(word: string) {
        var pattern = /^[0-9a-zA-Z]*$/g;
        return pattern.test(word);
    };

    static isNumber(word: any) {
        var pattern = /^[0-9]*$/g;
        return pattern.test(word);
    }
    static isEmpty(val: any) {
        let isArray = typeof (val);
        if (undefined === val || null === val || '' === val || (isArray && val.length == 0)) {
            return true;
        }
        return false;
    }

    static sortObject(o: Object) {
        return Object.keys(o).sort().map(key => ({ [key]: o[key] })).reduce((a, b) => ({ ...a, ...b }), {});
    }

    static hasProperty(o: Object, key: string) {
        if (this.isEmpty(o)) {
            return false;
        }
        for (let k in Object.keys(o)) {
            if (k === key) {
                return true;
            }
        }
        return false;
    }

    static formatHttpPrams(data: any): string {
        if (data) {
            var _type = typeof (data);
            if (_type == 'object') {
                var params = '';
                for (var key in Object.keys(data)) {
                    params += key + '=' + data[key] + '&';
                }
                return params;
            } else if (_type == 'string') {
                return data;
            } else {
                return "";
            }
        }
        return data;
    }

    static join(obj: any, separator: string) {
        separator = separator || ',';
        let result = '';
        if (obj) {
            for (let key in Object.keys(obj)) {
                result += key + '=' + obj[key] + separator;
            }
        }
        return result;
    }

    /**
   * 等待指定的时间
   * @param ms
   */
    static async sleep(ms: number) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve('');
            }, ms)
        });
    }

    static random(min: number, max: number) {
        var Range = max - min;
        var Rand = Math.random();
        return (min + Math.round(Rand * Range));
    }

    static shuffle<T>(src: Array<T>): Array<T> {
        if (!src) {
            return src;
        }
        src = src.slice();
        var target = new Array<T>(src.length);
        for (var i = 0, len = src.length; i < len; i++) {
            var j = Math.floor(Math.random() * src.length);
            target[i] = src[j];
            src.splice(j, 1);
        }
        return target
    }

    static extend(destination, source) {
        for (var property in source) {
            destination[property] = source[property]
        }
        return destination
    }

    static newInterval(callback: Function, interval: number) {
        return window.setInterval(function () {
            if (callback) {
                callback();
            }
        }, interval);
    }

    static copy<T>(target: T, src: T) {
        if (this.isEmpty(src) || this.isEmpty(target)) {
            return;
        }

        Object.keys(src).forEach(key => {
            let val = src[key];
            if (!Util.isEmpty(val)) {
                target[key] = val;
            }
        });

    }

    static copyWithNull<T>(target: T, src: T) {
        if (this.isEmpty(src) || this.isEmpty(target)) {
            return;
        }

        Object.keys(src).forEach(key => {
            target[key] = src[key];
        });

    }

    static copyList<T>(targetList: Array<T>, srcList: Array<T>, type: (new () => T), includeNull: boolean = false) {
        if (this.isEmpty(srcList)) {
            return;
        }
        srcList.forEach(src => {
            if (this.isBasicType(type)) {
                targetList.push(src);
            } else {
                let target = new type();
                if (includeNull) {
                    this.copyWithNull(target, src);
                } else {
                    this.copy(target, src);
                }
                targetList.push(target);
            }

        });
    }

    private static isBasicType(type: any): boolean {
        return type === String || type === Number || type === Boolean;
    }

    public static toMap<T>(ts: Array<T>, key: string): Map<number, T> {
        let map = new Map<number, T>();
        ts.map(item => {
            map.set(item[key], item)
        })
        return map;
    }

    public static copyMap<T>(target: Map<Object, T>, srcList: Array<T>, key: string) {
        if (this.isEmpty(srcList) || this.isEmpty(srcList)) {
            return target;
        }
        srcList.forEach(item => {
            target.set(item[key], item)
        });
    }

    public static distance(lat1, lng1, lat2, lng2) {
        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public static truncate(str: string, len: number) {
        if (Util.isEmpty(str)) {
            return '';
        }
        if (str.length <= len) {
            return str;
        }
        return str.substr(0, len) + "...";
    }

    public static getUrlParams(url: string) {
        let param = new Object();
        if (Util.isEmpty(url)) {
            return param;
        }

        url = decodeURIComponent(url);
        if (url.indexOf("?") != -1) {
            url = url.substr(url.indexOf("?") + 1);
        }
        let strs = url.split("&");
        for (var i = 0; i < strs.length; i++) {
            param[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
        }
        return param;
    }

    public static contains(aray: Array<Object>, obj: Object) {
        var index = aray.length;
        while (index--) {
            if (aray[index] === obj) {
                return true;
            }
        }
        return false;
    }

    public static randomList(src: Array<any>, count: number) {
        if (Util.isEmpty(src)) {
            return src;
        }
        let target = new Array<any>();
        count = count > src.length ? src.length : count;
        for (var i = 0; i < count; i++) {
            var j = Math.floor(Math.random() * src.length);
            target.push(src[j]);
            src.splice(j, 1);
        }
        return target
    }

    public static getPageParams(){
        const pages = getCurrentPages(); // 获取当前页面栈的实例列表
        const currentPage = pages[pages.length - 1]; // 获取当前页面的实例
        let options = currentPage.options; // 获取当前页面的参数
           if(Object.keys(options).length > 0){
            return options;
        }else{
            return null;
        }
    }

    /**
     * 格式化数字显示（万、千单位）
     * @param number 要格式化的数字
     * @returns 格式化后的字符串
     */
    public static formatNumber(number: number): string {
        if (number >= 10000) {
            return (number / 10000.0).toFixed(1) + '万';
        } else if (number >= 1000) {
            return (number / 1000.0).toFixed(1) + '千';
        } else {
            return number.toString();
        }
    }

    

}

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (element) {
    var index = this.indexOf(element);
    if (index > -1) {
        this.splice(index, 1);
        return true;
    }
    return false;

};

